package com.yihusitian.zsxq.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yihusitian.zsxq.mapper.TopicMapper;
import com.yihusitian.zsxq.pojo.data.GroupDO;
import com.yihusitian.zsxq.pojo.data.TalkDO;
import com.yihusitian.zsxq.pojo.data.TopicDO;
import com.yihusitian.zsxq.pojo.dto.Topic;
import com.yihusitian.zsxq.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description TODO
 * @Author LeeHo
 * @Date 2021-03-25 11:49:29
 */
@Slf4j
@Service
public class TopicServiceImpl extends ServiceImpl<TopicMapper, TopicDO> implements TopicService {

    @Autowired
    private TalkService talkService;

    @Autowired
    private GroupService groupService;

    @Autowired
    private AnswerService answerService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private TaskService taskService;

    @Override
    public TopicDO createTopic(Topic topic) {
        TopicDO topicDO = null;
        try {
            Long topicId = topic.getTopic_id();
            TopicDO oldTopicDO = getById(topicId);
            if (oldTopicDO != null) {
                System.out.println("主题" + topicId + "已经存过了");
                return null;
            }
            GroupDO groupDO = groupService.createGroup(topic.getGroup());
            TalkDO talkDO = talkService.createTalk(topic.getTalk());
            answerService.createAnswer(topic.getAnswer(), topicId);
            questionService.createQuestion(topic.getQuestion(), topicId);
            likeService.createLikes(topic.getLatest_likes(), topicId);
            commentService.createComments(topic.getShow_comments(), topicId);
            taskService.creatTask(topic.getTask(), topicId);
            topicDO = TopicDO.builder()
                    .id(topic.getTopic_id())
                    .type(topic.getType())
                    .commentsCount(topic.getComments_count())
                    .likeCount(topic.getLikes_count())
                    .readersCount(topic.getReaders_count())
                    .rewardsCount(topic.getRewards_count())
                    .readingCount(topic.getReading_count())
                    .groupId(groupDO == null ? 0L : groupDO.getId())
                    .talkId(talkDO == null ? 0L : talkDO.getId())
                    .createTime(topic.getCreateTime())
                    .modifyTime(topic.getModifyTime())
                    .build();
            topicDO.insert();
        } catch (Exception e) {
            log.error("topic异常了, topicId:{}", topic.getTopic_id(), e);
            throw new RuntimeException(e);
        }
        return topicDO;
    }
}